﻿using System.Data;
using System.Data.SqlClient;
using Framework;

namespace Enterprise
{
    public class AdminService : BaseService
    {
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="id">管理员ID</param>
        /// <param name="oldPassword">老密码</param>
        /// <param name="newsPassword">新密码</param>
        /// <returns></returns>
        public int ModifyPassword(int id, string oldPassword, string newsPassword)
        {
            Check.Argument.IsNotOutOfLength(oldPassword, 5, 20, "原密码");
            Check.Argument.IsNotOutOfLength(newsPassword, 5, 20, "新密码");
            var parameters = new[]
                {
                    new SqlParameter("@newpassword", SqlDbType.VarChar, 255),
                    new SqlParameter("@password",SqlDbType.VarChar, 255),
                    new SqlParameter("@id",SqlDbType.Int)

                };
            parameters[0].Value = newsPassword;
            parameters[1].Value = oldPassword;
            parameters[2].Value = id;
            var count = DbHelperSql.ExecuteSql("update tbadmin set copassword=@newpassword where copassword=@password and coadminid=@id", parameters);
            return count;
        }
        /// <summary>
        /// 获取管理员列表
        /// </summary>
        /// <returns>Table 返回一张表格</returns>
        public Table GetTable()
        {
            var table = new Table
            {
                Rows = DbHelperSql.Query("select * from tbadmin").Tables["ds"].Rows,
                Total = DbHelperSql.GetSingle("select count(*) from tbadmin").SafeToInt()
            };
            return table;
        }
        /// <summary>
        /// 根据ID获取一条记录
        /// </summary>
        /// <param name="id">管理员ID</param>
        /// <returns>DataRow 返回一条记录</returns>
        public DataRow GetById(int id)
        {
            return DbHelperSql.Query("select * from tbadmin where coadminId={0}".FormatWith(id)).Tables["ds"].Rows[0];
        }
        /// <summary>
        /// 登入
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">用户密码</param>
        /// <returns></returns>
        public bool Login(string username, string password)
        {
            var parameters = new[] { new SqlParameter("@username",SqlDbType.VarChar, 255) };
            parameters[0].Value = username;
            using (var sdr = DbHelperSql.ExecuteReader("select * from tbadmin where cousername=@username", parameters))
            {
                if (sdr.Read())
                {
                    if (sdr["CoPassword"].SafeToString() == password)
                    {
                        return true;
                    }
                    return false;
                }
            }
            return false;
        }
    }

}
